//
//  Filesystem.m
//  taptap-server
//
//  Created by Michael Humphris on 18/09/11.
//  Copyright 2011 DTERC. All rights reserved.
//

#import "Filesystem.h"

@implementation Filesystem

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

+(NSArray*)directoriesForPath:(NSString*)path{
    NSFileManager *fM = [NSFileManager defaultManager];
    NSArray* fileList = [[fM directoryContentsAtPath:path] retain];
    NSMutableArray *dirList = [[NSMutableArray alloc] init];
    
    for (NSString *file in fileList){
        NSString *p = [path stringByAppendingPathComponent:file];
        BOOL isDir = NO;
        [fM fileExistsAtPath:p isDirectory:(&isDir)];
        if(isDir) {
            [dirList addObject: [Path Combine:path path2:file]];
        }
    }
    return dirList;
}

+(BOOL)directoryExists:(NSString *)path{
    BOOL dir = FALSE;
    return ([[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&dir] && dir);
}

+(void)createDirectory:(NSString *)path{
    NSFileManager *fileManager= [NSFileManager defaultManager]; 
    BOOL isDir;
    if(![fileManager fileExistsAtPath:path isDirectory:&isDir])
        if(![fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:NULL])
            NSLog(@"Error: Create folder failed %@", path);
}

+(NSArray*)filesInDirectory:(NSString *)path isRecursive:(BOOL)recursive{
    NSMutableArray* outList = [[NSMutableArray alloc] init];
    
    NSFileManager *fM = [NSFileManager defaultManager];
    NSArray* fileList = [[fM directoryContentsAtPath:path] retain];
    
    for (NSString *file in fileList){
        NSString *p = [path stringByAppendingPathComponent:file];
        BOOL isDir = NO;
        [fM fileExistsAtPath:p isDirectory:(&isDir)];
        if(!isDir) {
            [outList addObject: [Path Combine:path path2:file]];
        } else {
            if (recursive) {
                [outList addObjectsFromArray:[self filesInDirectory:[Path Combine:path path2:file] isRecursive:recursive]];
            } 
        }
    }
    return [NSArray arrayWithArray:[outList autorelease]];

}
@end
